package org.kazuhiko.rpg.server.task.tasks;

import java.util.Iterator;
import java.util.Set;

import org.kazuhiko.rpg.server.Server;
import org.kazuhiko.rpg.server.model.Entity;
import org.kazuhiko.rpg.server.model.Player;
import org.kazuhiko.rpg.server.model.World;
import org.kazuhiko.rpg.server.task.ScheduledTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UpdateTask extends ScheduledTask
{
	private static final Logger logger = LoggerFactory.getLogger( UpdateTask.class );
	private static final long DELAY = 100;
	
	public UpdateTask()
	{
		super( DELAY );
	}

	@Override
	public void execute()
	{
		World[] worlds = Server.getServer().getWorlds();
		
		for( World world : worlds )
		{
			logger.trace( "Player list length: {}", world.getPlayerList().getPlayers().size() );
			
			for( Player player : world.getPlayerList().getPlayers() )
			{
				Set<Entity> localEntities = player.getLocalEntities();
				Iterator<Entity> localEntitiesIterator = localEntities.iterator();
				
				while( localEntitiesIterator.hasNext() )
				{
					Entity localEntity = localEntitiesIterator.next();
					if( localEntity.getId() == -1 )
					{
						localEntitiesIterator.remove();
						logger.trace( "Sending remove entity to other players" );
						player.getSession().getActionSender().sendRemoveEntity( localEntity );
					}
					else
					{
						logger.trace( "Sending updateEnttiy to other players" );
						player.getSession().getActionSender().sendUpdateEntity( localEntity );
					}
				}
				
				for( Player otherEntity : world.getPlayerList().getPlayers() )
				{
					if( !localEntities.contains( otherEntity ) )
					{
						localEntities.add( otherEntity );
						logger.trace( "Sending addEntity to other players" );
						player.getSession().getActionSender().sendAddEntity( otherEntity );
					}
				}
			}
			
			for( Player player : world.getPlayerList().getPlayers() )
			{
				player.resetToOldPosition();
				player.resetToOldRotation();
			}
		}
	}
	
}
